package com.health.home.service.lmpl;

import cn.hutool.core.lang.TypeReference;
import com.alibaba.fastjson.JSON;
import com.health.common.core.po.DiseasePo;
import com.health.common.core.utils.StringUtils;

import com.health.home.domain.vo.DiseaseVo;
import com.health.home.mapper.DiseaseMapper;
import com.health.home.service.DiseaseService;
import com.health.home.util.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author xpz
 * @date 2024/12/11 12:29
 */
@Service
@Slf4j
public class DiseaseServicelmpl   implements DiseaseService{

    @Autowired
    private DiseaseMapper diseaseMapper;

    @Autowired
    private StringRedisTemplate redisTemplate;

    private static final String CACHE_KEY_PREFIX = "diseaseId:";
    @Override
    public List<DiseasePo> diseaseList() {
        List<DiseasePo> list = diseaseMapper.diseaseList();
        return list;
    }

    @Override
    public List<DiseasePo> diseaseLists(DiseaseVo diseaseVo) {

        //构建redis中的key
        String redisKey = "diseasePoLists"+diseaseVo.getDiseaseName()+diseaseVo.getPageNum()+diseaseVo.getPageSize();
        // 尝试从 Redis 缓存中获取数据
        String cachedData = redisTemplate.opsForValue().get(redisKey);
        if (cachedData != null) {
            List<DiseasePo> diseasePoList = JSON.parseObject(cachedData, new TypeReference<List<DiseasePo>>() {
            });
            return diseasePoList;
        }
        // 如果Redis中没有数据，从数据库查
        List<DiseasePo> list = diseaseMapper.diseaseLists(diseaseVo);
        // 返回数据库查询结
        return list;
    }

    @Override
    public Result diseaseAdd(DiseasePo diseasePo) {
        if (StringUtils.isEmpty(diseasePo.getDiseaseName())){
            return Result.error("疾病名称不能为空");
        }
        if (StringUtils.isEmpty(diseasePo.getPathology())){
            return Result.error("病理描述不能为空");
        }
        if (StringUtils.isEmpty(diseasePo.getSymptoms())){
            return Result.error("症状描述不能为空");
        }
        if (StringUtils.isEmpty(diseasePo.getDosAndDonts())){
            return Result.error("宜与忌不能为空");
        }
        if (StringUtils.isEmpty(diseasePo.getWesternMedicineTreatment())){
            return Result.error("西药治疗方案不能为空");
        }
        // 校验疾病名称是否已经存在
//        if (diseaseMapper.diseaseExistsByName(diseasePo.getDiseaseName())) {
//            return Result.error("疾病名称已存在，请选择其他名称");
//        }
        try {
            diseaseMapper.diseaseAdd(diseasePo);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return Result.success();
    }

    @Override
    public Result diseaseUpdate(DiseasePo diseasePo) {
        if (StringUtils.isEmpty(diseasePo.getDiseaseName())){
            return Result.error("疾病名称不能为空");
        }
        if (StringUtils.isEmpty(diseasePo.getPathology())){
            return Result.error("病理描述不能为空");
        }
        if (StringUtils.isEmpty(diseasePo.getSymptoms())){
            return Result.error("症状描述不能为空");
        }
        if (StringUtils.isEmpty(diseasePo.getDosAndDonts())){
            return Result.error("宜与忌不能为空");
        }
        if (StringUtils.isEmpty(diseasePo.getWesternMedicineTreatment())){
            return Result.error("西药治疗方案不能为空");
        }
        diseaseMapper.diseaseUpdate(diseasePo);
        return Result.success();
    }

    @Override
    public void removeById(Integer id) {
        String cacheKey=CACHE_KEY_PREFIX+id;
        //第一次删除缓存 在操作数据库之前
        redisTemplate.delete(cacheKey);
        try {
            int i = diseaseMapper.removeByIdDelete(id);
            if (i>0){
                // 第二次删除缓存（在数据库操作之后）
                redisTemplate.delete(cacheKey);
                log.info("病症信息删除成功: {}", id);
            }else {
                log.warn("病症信息删除失败，未找到要删除的记录: {}", id);
            }
        } catch (Exception e) {
            log.error("病症信息删除失败，错误信息：{}", e.getMessage(), e);

        }
    }

}
